import { View, Picker, Input, Text, RadioGroup, Textarea, Radio } from "@tarojs/components"
import { useEffect, useReducer, useState } from "react"
import { AtButton } from 'taro-ui'
import Taro, { useReady, useRouter } from '@tarojs/taro'

import XModuleHeader from "../../../../components/XModuleHeader"
import XFormItem from '../../../../components/XFormItem'
import { DEVICE_TYPE } from '../../../../config/Device'
import { STRATEGY_TYPE } from '../../../../config/Strategy'
import { hideLoading, reducer, showLoading, showModal, showToast } from '../../../../utils'
import { Strategy } from '../../../../types/Strategy'

import './index.scss'
import { saveChargeStrategyApi } from "../../../../services/ChargeStrategy"
import GlobalData from "../../../../global"

export default (props : {
    strategy?:Strategy | null;
    onFinish : {
        (strategy:Strategy|null) : void
    }
}) => {
    let strategyId:number = props.strategy ? props.strategy.strategyId as number : 0
    let initFormData:Strategy = {
        // vehicleType : '',
        // deviceModel : '',
        strategyType : STRATEGY_TYPE[0].code,
        strategyName : '',
        unitPrice : '',
        settleUnit : 1,
        maxPower : '',
        minPower : '',
        cardChargeAmount : '',
        rules : [{w : '', a : ''}],
        options : [],
        remark : ''
    }
    
    let [deviceTypeText, setdeviceTypeText] = useState('')
    let [deviceTypeValue, setdeviceTypeValue] = useState<number[]>([0, 0])
    let [deviceTypeRange, setdeviceTypeRange] = useState([DEVICE_TYPE, DEVICE_TYPE[0].children])
    let [formData, formDataDispatch] = useReducer(reducer, initFormData)
    const UnitName = () => {
        return <>
            {formData.strategyType == 1 ? '分钟' : '度'}
        </>
    }

    function changeInput(data:{[key in keyof Strategy]:any}) {
        formDataDispatch(data)
    }

    function selectedDeviceTypeColumn(e:{column:number; value:number}) { //选择设备类型，列的变动
        if(e.column == 0) {
            setdeviceTypeRange([DEVICE_TYPE, DEVICE_TYPE[e.value].children])
            deviceTypeValue[0] = e.value
        }else {
            deviceTypeValue[1] = e.value 
        }

        setdeviceTypeValue([...deviceTypeValue])
    }
    function confirmDeviceType(value:number[]) {
        setdeviceTypeValue(value)
        changeInput({vehicleType : DEVICE_TYPE[value[0]].code, deviceModel : DEVICE_TYPE[value[0]].children[value[1]].code})
        setdeviceTypeText(DEVICE_TYPE[value[0]].label + '/' + DEVICE_TYPE[value[0]].children[value[1]].label)
    }

    function addStrategyRule() {
        formData.rules.push({w : '', a : ''})
        changeInput({rules : formData.rules})
    }
    function removeStrategyRule(index:number) {
        formData.rules.splice(index, 1)
        changeInput({rules : formData.rules})
    }
    function inputStrateRule(index:number, k:'w'|'a', v:number|string) {
        formData.rules[index][k] = v
        changeInput({rules : formData.rules})
    }

    function addOption() {
        formData.options.push('')
        changeInput({options : formData.options})
    }
    function removeOption(index:number) {
        formData.options.splice(index, 1)
        changeInput({options : formData.options})
    }
    function inputOption(index:number, v:number|string) {
        formData.options[index] = v
        changeInput({options : formData.options})
    }


    async function submit() {
        let data:Strategy = JSON.parse(JSON.stringify(formData))
        for(let k in  data) {
            if(k == 'rules' || k == 'options' || k == 'remark') {

            }else {
                if(data[k] === '') {
                    Taro.showToast({
                        icon : 'none',
                        title : '请填写完整的数据'
                    })
                    return
                }
            }
        }

        if(data.strategyType == 1) {
            if(data.rules) {
                for(let i = 0; i < data.rules.length; i ++) {
                    if(data.rules[i].w == '' || data.rules[i].a == '') {
                        Taro.showToast({
                            icon : 'none',
                            title : '请填写完整的策略数据'
                        })
                        return
                    }
                }
            }
            
        }

        if(data.options) {
            for(let i = 0; i < data.options.length; i ++) {
                if(data.options[i] === '') {
                    Taro.showToast({
                        icon : 'none',
                        title : '请整写预设选项数据'
                    })
                    return
                }
            }
        }
        

        if(props.strategy) { //编辑
            let updateData:Strategy = {}
            for(let k in data) {
                if(JSON.stringify(data[k]) != JSON.stringify(props.strategy[k])) {
                    updateData[k] = data[k]
                }
            }

            if(Object.keys(updateData).length == 0) {
                props.onFinish(null)
                return
            }

            updateData.strategyId = strategyId

            data = updateData
        }

        showLoading()
        const res = await saveChargeStrategyApi(data)
        hideLoading()
        if(!res.success) {
            showModal(res.msg)
        }else {
            if(data.strategyId) { //编辑

            }else {
                data.strategyId = res.data
            }
            props.onFinish(data)
            showToast('保存成功')
        }

    }

    useEffect(() => {
        if(props.strategy) {
            let strategy = props.strategy
            for(let k in formData) {
                if(strategy[k] != null) {
                    formData[k] = strategy[k]
                }
            }

            formDataDispatch({...formData})
        }
    }, [])
    
    return <>
        <View className='page-view'>
            <View>
                <View className='module' style='padding-bottom:0;'>
                    <XModuleHeader>基本信息</XModuleHeader>
                    {/* <XFormItem required label='设备类型'>
                        <Picker mode='multiSelector' range-key='label' range={deviceTypeRange} onColumnChange={e => selectedDeviceTypeColumn(e.detail)} onChange={e => { confirmDeviceType(e.detail.value)}} value={deviceTypeValue}>
                            <Input disabled placeholder='请选择设备类型' value={deviceTypeText}  />
                        </Picker>
                    </XFormItem> */}
                    <XFormItem required label='策略类型'>
                        <View className='form-item flex-align-items-center'>
                            <RadioGroup onChange={e => { changeInput({strategyType: e.detail.value})}}>
                                {/* {
                                    STRATEGY_TYPE.map((strategy, index) => {
                                        let className = index > 0 ? 'm-l-30' : ''
                                        return <Radio disabled={strategyId > 0} className={className} value={String(strategy.code)} checked={formData.strategyType == strategy.code}>{strategy.label}</Radio>
                                    })
                                } */}
                                {
                                    Object.keys(GlobalData.strategyType).map((key, index) => {
                                        let className = index > 0 ? 'm-l-30' : ''
                                        return <Radio disabled={strategyId > 0} className={className} value={key} checked={formData.strategyType == key}>{GlobalData.strategyType[key].name}</Radio>
                                    })
                                }
                            </RadioGroup>
                        </View>
                    </XFormItem>
                    <XFormItem required label='策略名称'>
                        <View className='form-item'>
                            <Input type='text' placeholder='请填写策略名称' value={formData.strategyName} onInput={e => { changeInput({strategyName: e.detail.value})}} />
                        </View>
                    </XFormItem>
                    <XFormItem required label='单价'>
                        <View className='form-item flex-align-items-center'>
                            <Input type='digit' className='flex-1' placeholder='请填写单价' value={formData.unitPrice} onInput={e => {let v = e.detail.value ; changeInput({unitPrice: v === '' ? v : Number(v)})}} />
                            <View className='m-l-30'>元/{formData.strategyType == 1 ? '小时' : '度'}</View>
                        </View>
                    </XFormItem>
                    <XFormItem required label='计费单位'>
                        <View className='form-item flex-align-items-center'>
                            <Input type='digit' className='flex-1' placeholder='计费单位' value={formData.settleUnit} onInput={e => {let v = e.detail.value ; changeInput({settleUnit: v === '' ? v : Number(v)})}} />
                            <View className='m-l-30'><UnitName></UnitName></View>
                        </View>
                    </XFormItem>
                    <XFormItem required label='最大功率'>
                        <View className='form-item flex-align-items-center'>
                            <Input type='digit' className='flex-1' placeholder='请填写最大功率' value={formData.maxPower} onInput={e => {let v = e.detail.value ; changeInput({maxPower: v === '' ? v : Number(v)})}} />
                            <View className='m-l-30'>W</View>
                        </View>
                    </XFormItem>
                    <XFormItem required label='最小功率'>
                        <View className='form-item flex-align-items-center'>
                            <Input type='digit' className='flex-1' placeholder='请填写最小功率' value={formData.minPower} onInput={e => {let v = e.detail.value ; changeInput({minPower: v === '' ? v : Number(v)})}} />
                            <View className='m-l-30'>W</View>
                        </View>
                    </XFormItem>
                    <XFormItem required  border={false} label='刷卡预付费'>
                        <View className='form-item flex-align-items-center'>
                            <Input type='digit' className='flex-1' placeholder='请填写刷卡预付费' value={formData.cardChargeAmount} onInput={e => {let v = e.detail.value ; changeInput({cardChargeAmount: v === '' ? v : Number(v)})}} />
                            <View className='m-l-30'>元</View>
                        </View>
                    </XFormItem>
                </View>
                <View className='m-t-30'>
                    <View className='module'>
                        <XModuleHeader>充电策略说明<Text className='f-28 color-999'>（选填）</Text></XModuleHeader>
                        <View className='m-t-30'>
                            <Textarea className='remark' value={formData.remark}  onInput={e => { changeInput({remark: e.detail.value})}}></Textarea>
                        </View>
                    </View>
                </View>
                {formData.strategyType == 1 &&
                    <View className='m-t-30'>
                        <View className='module'>
                            <XModuleHeader>策略规则<Text className='f-28 color-999'>（最少一项，最多四项）</Text></XModuleHeader>
                            <View className='m-t-30'>
                                {
                                    formData.rules.map((rule, index) => <View className='strategy-rule flex-align-items-center'>
                                            <Input className='flex-1 text-center border' type='digit' value={rule.w} onInput={e => { inputStrateRule(index, 'w', e.detail.value) }} placeholder='功率' />
                                            <View className='m-l-20'>W</View>
                                            <Input className='flex-1 text-center border m-l-20' type='digit' value={rule.a} onInput={e => { inputStrateRule(index, 'a', e.detail.value) }} placeholder='金额' />
                                            <View className='m-l-20'>元/小时</View>
                                            {formData.rules.length > 1 &&
                                                <View className='at-icon at-icon-close m-l-30 color-f56c6c f-36' onClick={() => { removeStrategyRule(index) }}></View>
                                            }
                                        </View>
                                    )
                                }
                            </View>
                            
                        </View>
                        {formData.rules.length < 4 &&
                            <View className='add-button' onClick={addStrategyRule}>添加规则</View>
                        }
                    </View>
                }
                <View className='m-t-30'>
                    <View className='module'>
                        <XModuleHeader>充值预设选项<Text className='f-28 color-999'>（选填）</Text></XModuleHeader>
                        <View className='m-t-30'>
                            <View className='options'>
                                {
                                    formData.options.map((option, index) => <View>
                                        <View className='flex-align-items-center'>
                                            <Input className='flex-1 text-center border' value={option} onInput={e => { inputOption(index, e.detail.value) }} type='digit'/>
                                            <View className='m-l-10'>元</View>
                                            <View className='at-icon at-icon-close m-l-20 color-f56c6c f-36' onClick={() => { removeOption(index) }}></View>
                                        </View>
                                    </View>)
                                }
                            </View>
                        </View>
                    </View>
                    <View className='add-button' onClick={addOption}>添加预设</View>
                </View>
            </View>


            <View className='m-t-60 p-l-r'>
                <AtButton type='primary' circle onClick={submit}>保 存</AtButton>
            </View>

        </View>
    </>
}